var db = require('./db');
var mongodb = new db();
var ObjectID = require("mongodb").ObjectID;
var cfmIndex = require('./cfmIndex.js');
var increment = 0x1;
var regex = /^_/;
var logger = require('../models/logger.js');

//基本实现
exports.create= function createCD(data,callback){
    mongodb.getCollection('cfm',function(collection){
        //首先查找同名元素
        checkCDExistence(data[0].name,collection,function(err,doc){
            if(err != null){
                return callback(err,doc);
            }
            else if(doc.length != 0){
                err = "already Exist";
                return callback(err,doc);
            }
            else{
                var cfmData = {
                    user: data.user,
                    cd : {}
                }
                cfmData["cd"][data.cd] = {
                    _description : data.description
                }

                collection.insert(cfmData, {safe: true}, function(err, doc) {
                    logger.generateLogData('INFO','cfm','insert',cfmData);
                    cfmIndex.create(doc[0],function(err2,doc2){
                        return callback(err, doc);
                    });
                });
            }
        });
    });
};

exports.addastest = function addastest(filter,callback){
    mongodb.getCollection('cfm',function(collection){
        collection.update(filter[0],{"$set" : filter[1]}, {safe: true}, function(err, doc) {
            logger.generateLogData('INFO','cfm','update',[filter[0],{"$set" : filter[1]}]);
            return callback();
        });
    });
}

exports.remove = function removeCfm(filter,callback){
    mongodb.getCollection('cfm',function(collection){
        collection.remove(filter[0],function(err){
            if (err) {
                console.warn(err.message);
                return callback();
            }
            else {
                logger.generateLogData('INFO','cfm','remove',filter[0]);
                console.log('cfm successfully removed');
                cfmIndex.remove(filter[0],function(){
                    return callback();
                });
            }
        });
    });
};

exports.get = function getCD(filter,callback){
    mongodb.getCollection('cfm',function(collection){
        collection.findOne(filter, function(err, doc) {
            if(err != null){
                return callback(err, doc);
            }
            if(doc === null){
                err = "not Exist";
                return callback(err, doc);
            }
            return callback(err, doc);
        });
    });
};

exports.newElement = function newElement(filter,callback){
    mongodb.getCollection('cfm',function(collection){
        var elemID = generateID(filter.type,filter.value);
        //进行添加
        var newElement = {};
        newElement[filter.dir+"."+elemID] = generateElem(filter,1);

        collection.update({_id:filter._id},{"$set":newElement},{safe:true},function(err,count) {
            logger.generateLogData('INFO','cfm','update',[{_id:filter._id},{"$set":newElement}]);
            if (err) console.warn(err.message);
            else console.log('cfm successfully get newElement');
            return callback(err,filter.dir+"."+elemID);
        });
    });
}

exports.add= function addElem(collectionName,filter,callback){
    console.log(filter[0]);
    console.log(filter[1]);
    mongodb.getCollection('cfm_'+collectionName,function(collection){
        collection.update( filter[0],{"$inc":filter[1]},{safe:true},function(err,number) {
            logger.generateLogData('INFO','cfm_'+collectionName,'update',[filter[0],{"$inc":filter[1]}]);
            //if (err) console.warn(err.message);
            //else console.log('cfm successfully updated');
            callback(err,number);
        });
    });
};

exports.add2= function addElem2(filter,callback){
//用于同时添加两个元素的，针对那些名称加数据同时添加的情况
    var x = filter[0];
    var y ={};
    y[filter[1]]=1;
    y[filter[2]]=1;
    mongodb.getCollection('cfm',function(collection){
        collection.update( x,{"$inc":y},{safe:true},function(err,number) {
            logger.generateLogData('INFO','cfm','update',[x,{"$inc":y}]);
            if (err) console.warn(err.message);
            else console.log('cfm successfully updated');
            //console.log(number); //多个添加仍为1
            callback(err,number);
        });
    });
};

exports.ref= function refElem(collectionName,filter,subFilter,callback){
//去引用，包括底层元素的自动去除
    mongodb.getCollection('cfm_'+collectionName,function(collection){
        collection.update(filter,{"$inc":subFilter},{safe:true},function(err,number) {
            logger.generateLogData('INFO','cfm_'+collectionName,'update',[filter,{"$inc":subFilter}]);
            if (err) console.warn(err.message);
            else console.log('cfm successfully deleted');
            console.log(number)
            return callback(err,number);
        });
    });
};

exports.generateSubFilter = function generateSubFilter(sub,callback){
    var subFilter=[];
    //var preFilter=".";
    var preFilter="";
    generateFilter(sub,preFilter,subFilter);
    return callback(subFilter);
};

generateFilter = function(sub,preFilter,subFilter){
    if(typeof sub === 'string') return;
    for(var key in sub){
        if(key === '_nor'){
            subFilter[subFilter.length] = preFilter+key
        }
        else{
            generateFilter(sub[key],preFilter+key+".",subFilter);
        }
    }
}
//New One
checkCDExistence = function(_cdName,collection,callback){
    return callback(null,[]);
    //验证通过
    /*
    collection.find({"$where":function(){
        for(var cdName in this.cd){
            if(_cdName === cdName) {
                return true;
            }
        };
        return false;
    }}).toArray(function(err,doc){
        return callback(err,doc);
    });
    */
};

exports.generateItem = function(collectionName,callback){
    mongodb.getCollection('cfm_'+collectionName,function(collection){
        //var cfmData = {name:data.source.name};
        var cfmData = {};
        collection.insert(cfmData, {safe: true}, function(err, doc) {
            logger.generateLogData('INFO','cfm_'+collectionName,'insert',cfmData);
            return callback(err, doc);
        });
    });
}

exports.setNor = function(cfm,dir){
    for(var key in dir){
        var splitedKey = key.split(".");
        var root = cfm;
        for(var j=0;j<splitedKey.length;j++){
            root = root[splitedKey[j]];
            if(root === undefined) break;
        }
        if(root === undefined) {
            dir[key] = 1;
        }else{
            dir[key] = root+1;//以为之后cfm要添加
        }

    }
}